package com.x86.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.x86.domain.User;
import com.x86.domain.UserLoginLog;
import com.x86.domain.UserVO;
import com.x86.mapper.UserLoginLogMapper;
import com.x86.util.JwtUtil;
import com.x86.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.x86.mapper.UserMapper;
import com.x86.service.UserService;

import java.util.HashMap;

/**
 * @author 风亦未止
 * @date 2022/4/10 19:27
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
     @Autowired
     public UserLoginLogMapper userLoginLogMapper;

    @Override
    public ResponseResult login(String nickname, String password) {
        User one = lambdaQuery().eq(User::getNickname, nickname).one();
        if (ObjectUtil.isNull(one)) return ResponseResult.failure("用户不存在");
        if (password.equals(one.getPassword())) {
            String token = JwtUtil.getTokenByUser(one);
            HashMap<String, Object> data = new HashMap<>();
            data.put("username",one.getName());
            data.put("Token",token);
            return ResponseResult.success("登录成功！", data);
        }
        return ResponseResult.failure("密码错误！");
    }

    @Override
    public ResponseResult login(UserVO user, String ip, String ipInfo) {
        User userInfo = lambdaQuery().eq(User::getNickname, user.getNickname()).one();
        if (ObjectUtil.isNull(userInfo)) return ResponseResult.failure("用户不存在");
        if (user.getPassword().equals(userInfo.getPassword())) {
            UserLoginLog userLoginLog = new UserLoginLog();
            userLoginLog.setUserid(userInfo.getId());
            userLoginLog.setIp(ip);
            userLoginLog.setAddress(ipInfo);
            userLoginLog.setDevice(user.getDevice());
            userLoginLog.setOs(user.getOs());
            userLoginLog.setTime(DateUtil.now());
            userLoginLogMapper.insert(userLoginLog);
            String token = JwtUtil.getTokenByUser(userInfo);
            HashMap<String, Object> data = new HashMap<>();
            data.put("username",userInfo.getName());
            data.put("Token",token);
            return ResponseResult.success("登录成功！", data);
        }
        return ResponseResult.failure("密码错误！");
    }
}

